package com.hykj.coca.config;

import com.alibaba.fastjson.JSON;
import com.hykj.coca.model.UserModel;
import com.hykj.coca.result.AppBack;
import com.hykj.coca.service.AdminService;
import com.hykj.coca.service.UserService;
import com.hykj.coca.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

import static com.hykj.coca.utils.Util.returnJson;


/**
 * Created by Administrator on 2017/5/22 0022.
 */
@Component
public class MobileApiInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(MobileApiInterceptor.class);

    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, String[]> map = request.getParameterMap();
        String userIds[] = map.get("userId");
        if (userIds == null) {
            return true;
        }
        if(StringUtil.isEmptyString(userIds[0])){
            return true;
        }
        Integer userId = Integer.valueOf(userIds[0]);
        String tokens[] = map.get("token");

        if (tokens == null) {
            AppBack appBack = new AppBack(-96, "请传token");
            returnJson(response, JSON.toJSONString(appBack));
            return false;
        }
        String token = tokens[0];
        UserModel user = new UserModel();
        user.setId(userId);
        user.setToken(token);
        if (userService.getByToken(user) == null) {
            returnJson(response, JSON.toJSONString(new AppBack(-95, "登录过期")));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }


}